import React, { useState, useEffect } from 'react';
import { Table, Button, Tag, Modal, Descriptions, message, Space, Popconfirm } from 'antd';
import { ClockCircleOutlined, CheckCircleOutlined, CloseCircleOutlined, EyeOutlined } from '@ant-design/icons';

const statusMap = {
  PENDING: { color: 'orange', text: '待审核' },
  APPROVED: { color: 'green', text: '等待用户退货' }, // 修改状态显示文本为"等待用户退货"
  REJECTED: { color: 'red', text: '已驳回' },
  RETURNING: { color: 'blue', text: '退货中，等待商家确认' }, // 调整状态描述
  REFUNDED: { color: 'purple', text: '已退款' }
};

const typeMap = {
  refund: '仅退款',
  return: '退货退款'
};

const AfterSales = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detail, setDetail] = useState(null);
  const [detailVisible, setDetailVisible] = useState(false);

  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    setLoading(true);
    const afterSales = JSON.parse(localStorage.getItem('afterSales') || '[]');
    setData(afterSales);
    setLoading(false);
  };

  const updateStatus = (id, status) => {
    const afterSales = JSON.parse(localStorage.getItem('afterSales') || '[]');
    const idx = afterSales.findIndex(item => item.id === id);
    if (idx !== -1) {
      afterSales[idx].status = status;
      localStorage.setItem('afterSales', JSON.stringify(afterSales));
      loadData();
    }
  };

  const handleApprove = (record) => {
    // 退货退款类型审核通过后先进入"APPROVED"（等待用户退货）状态
    const newStatus = record.type === 'return' ? 'APPROVED' : 'REFUNDED';
    updateStatus(record.id, newStatus);
    message.success('审核通过');
  };
  

  const handleReject = (record) => {
    updateStatus(record.id, 'REJECTED');
    message.info('已驳回');
  };

  const handleConfirmReceive = (record) => {
    const afterSales = JSON.parse(localStorage.getItem('afterSales') || '[]');
    const idx = afterSales.findIndex(item => item.id === record.id);
    if (idx !== -1) {
      afterSales[idx].status = 'REFUNDED'; // 关键修改：状态改为已退款
      localStorage.setItem('afterSales', JSON.stringify(afterSales));
      message.success('已确认收货，退款到账');
      loadData();
    }
  };

  const columns = [
    { title: '售后单号', dataIndex: 'id', key: 'id', width: 120 },
    { title: '订单号', dataIndex: 'orderId', key: 'orderId', width: 120 },
    { title: '类型', dataIndex: 'type', key: 'type', render: t => typeMap[t] },
    { title: '状态', dataIndex: 'status', key: 'status', render: s => <Tag color={statusMap[s]?.color}>{statusMap[s]?.text || s}</Tag> },
    { title: '物流公司', dataIndex: ['logistics', 'company'], key: 'logisticsCompany', render: (v, r) => r.logistics?.company || '-' },
    { title: '运单号', dataIndex: ['logistics', 'trackingNumber'], key: 'logisticsTracking', render: (v, r) => r.logistics?.trackingNumber || '-' },
    { title: '申请时间', dataIndex: 'createTime', key: 'createTime', render: t => new Date(t).toLocaleString() },
    {
      title: '操作',
      key: 'action',
      width: 220,
      render: (_, record) => (
        <Space>

          {record.status === 'PENDING' && (
            <>
              <Popconfirm title="确定通过审核？" onConfirm={() => handleApprove(record)}>
                <Button icon={<CheckCircleOutlined />} type="primary" size="small" style={{ height: 22, padding: 12 }}>通过</Button>
              </Popconfirm>
              <Popconfirm title="确定驳回？" onConfirm={() => handleReject(record)}>
                <Button icon={<CloseCircleOutlined />} danger size="small">驳回</Button>
              </Popconfirm>
            </>
          )}
          <Button icon={<EyeOutlined />} size="small" onClick={() => { setDetail(record); setDetailVisible(true); }}>详情</Button>


          {/* 仅当售后类型为退货退款且状态为"RETURNING"（退货中）时显示确认收货按钮 */}
          {record.type === 'return' && record.status === 'RETURNING' && (
            <Popconfirm title="确认已收到退货商品？" onConfirm={() => handleConfirmReceive(record)}>
              <Button icon={<CheckCircleOutlined />} type="primary" size="small">确认收货</Button>
            </Popconfirm>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <h2 style={{ marginBottom: 24 }}>售后管理</h2>
      {data.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px' }}>暂无售后数据</div>
      ) : (
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
          bordered
        />
      )}
      <Modal
        title="售后详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={600}
      >
        {detail && (
          <Descriptions bordered column={1} size="small">
            <Descriptions.Item label="售后单号">{detail.id}</Descriptions.Item>
            <Descriptions.Item label="订单号">{detail.orderId}</Descriptions.Item>
            <Descriptions.Item label="类型">{typeMap[detail.type]}</Descriptions.Item>
            <Descriptions.Item label="状态"><Tag color={statusMap[detail.status]?.color}>{statusMap[detail.status]?.text}</Tag></Descriptions.Item>
            <Descriptions.Item label="申请时间">{new Date(detail.createTime).toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="退款原因">{detail.reason}</Descriptions.Item>
            <Descriptions.Item label="问题描述">{detail.description}</Descriptions.Item>
            {detail.logistics && (
              <>
                <Descriptions.Item label="物流公司">{detail.logistics.company}</Descriptions.Item>
                <Descriptions.Item label="运单号">{detail.logistics.trackingNumber}</Descriptions.Item>
              </>
            )}
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default AfterSales;
